# 单一条件

x <- c(1, 3, 7, 2, 6, 4)  
result <- which(x > 5)
result

# 多条件

x <- c(1, 3, 7, 2, 6, 4)  
result <- which(x > 3 & x < 7)  
result

# ------------------------------------------
# 准备工作
# ------------------------------------------

setwd("/Users/eimei/Documents/Rdata/")  # 设定工作空间
data <- read.csv("HRdata.csv")  # 读取数据

newdata <- data[c("EmployeeNumber", "Age", "Department",
                  "EnvironmentSatisfaction", "JobSatisfaction",
                  "MonthlyIncome", "RelationshipSatisfaction")]

head(newdata)

# ------------------------------------------
# which的作用过程
# ------------------------------------------

temp <- newdata[1:6, ]
temp1 <- temp[which(temp$Department == "Research & Development" & 
                      temp$Age > 30),]
temp1

temp$Department == "Research & Development"
temp$Age > 30

c(FALSE, TRUE, TRUE, TRUE, TRUE, TRUE) &  c(TRUE, TRUE, TRUE, TRUE, FALSE, TRUE)

which(c(FALSE, TRUE, TRUE, TRUE, TRUE, TRUE) &  c(TRUE, TRUE, TRUE, TRUE, FALSE, TRUE))

temp1 <- temp[c(2, 3, 4, 6), ]

# ------------------------------------------
# 任务一
# ------------------------------------------
Task1 <- newdata[which(newdata$Department == "Sales"),]

# ------------------------------------------
# 任务二
# ------------------------------------------
Task2 <- newdata[which(newdata$Age >= 30 & newdata$Age <= 50),]

# ------------------------------------------
# 任务三
# ------------------------------------------
summary(newdata)

Task3 <- subset(newdata, MonthlyIncome < 2911 | MonthlyIncome > 8379, 
                select = c("EnvironmentSatisfaction", "JobSatisfaction", "MonthlyIncome", "RelationshipSatisfaction"))
str(Task3)

Task3 <- subset(newdata, MonthlyIncome < 2911 | MonthlyIncome > 8379, 
                select = EnvironmentSatisfaction : RelationshipSatisfaction)
str(Task3)